package com.xc.common.interceptor;

import com.google.common.collect.Maps;
import com.xc.pojo.AgentUser;
import com.xc.pojo.SiteAdmin;
import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.CookieUtils;
import com.xc.utils.redis.JsonUtil;
import com.xc.utils.redis.RedisShardedPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;
/**
 * @author mipha
 * @version 1.0
 * @date 2019/2/28 11:28 AM
 */
@Slf4j
public class ApiAdminAuthorityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest
            , HttpServletResponse httpServletResponse, Object handler) throws Exception {

//        log.info("请求进入 ApiAdminAuthorityInterceptor ...");

        //  开始处理业务逻辑-----------------------------------------------------------------------
        SiteAdmin siteAdmin = null;
        String loginToken = CookieUtils
                .readLoginToken(httpServletRequest
                        , PropertiesUtil.getProperty("admin.cookie.name"));
//        log.info("admin loginToken = {}" , loginToken);

        if(StringUtils.isNotEmpty(loginToken)){
            String adminJsonStr = RedisShardedPoolUtils.get(loginToken);
//            log.info("=================拦截器拦截到 admin ：{}=====================",adminJsonStr);
            siteAdmin = JsonUtil.string2Obj(adminJsonStr , SiteAdmin.class);
        }

        if(null == siteAdmin){
            log.info("authority: admin 为空");
            //  首先重置response,否则会报异常 getWriter() has been called for this response;
            httpServletResponse.reset();
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json;charset=UTF-8");

            PrintWriter writer = httpServletResponse.getWriter();

            Map map = Maps.newHashMap();
            map.put("success" , false);
            map.put("msg" , "请先登录，无权限访问admin");
            writer.print(JsonUtil.obj2String(map));

            writer.flush();
            writer.close();
            //  返回false，不会进入controlelr
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("=============================postHandle=============================");
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
//        log.info("=============================afterCompletion=============================");
    }



}